//
//  InventoryViewControllerLater.m
//  PCS-IPHONE
//
//  Created by zhouChaoLin on 17/3/11.
//  Copyright © 2017年 Henry. All rights reserved.
//

#import "InventoryViewControllerLater.h"
#import "SellingViewController.h"
#import "PickingInventory.h"
#import "Invertory.h"
#import "AddInventoryViewController.h"
#import "Stock.h"

@interface InventoryViewControllerLater (){
    __weak IBOutlet UITableView *_tableView;
    UITextField  *textNumBer;
    Stock  *currentStock;

}
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *viewHeight;

@property (weak, nonatomic) IBOutlet UIButton *btnSubmit;

@property (weak, nonatomic) IBOutlet UIButton *btnCancel;

@property(nonatomic,strong)NSMutableArray  *arrStock;
@property(nonatomic,strong)NSMutableArray  *arrMainData;



@property (weak, nonatomic) IBOutlet UILabel *lablePeiSong;
@property (weak, nonatomic) IBOutlet UILabel *lablePanDian;


@end

@implementation InventoryViewControllerLater

@synthesize  btnSubmit,btnCancel,arrMainData ;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self  initDataAndUI];

}

-(void)initDataAndUI{
    
    [_tableView setTranslatesAutoresizingMaskIntoConstraints:NO];
    
    VIEW_CORNER(btnSubmit, buttonCorner21);
    btnSubmit.backgroundColor=NORMAL_BULUE_COLOR;
    
    VIEW_CORNER(btnCancel,buttonCorner21);
    btnCancel.layer.masksToBounds=YES;
    btnCancel.layer.borderColor=NORMAL_BULUE_COLOR.CGColor;
    btnCancel.layer.borderWidth=1.0;
    VIEW_CORNER(self.viewBG, 4.0);
    VIEW_CORNER(self.lableSelectTitle, 4.0);
   
    arrMainData=[NSMutableArray new];
    HangBanInfo  *hangBan=[HangBanInfo currentHangBan];
    if ([hangBan.FIsInventoryHS  isEqualToString:@"1"]) {
        self.ViewBottom.hidden=YES;
    }
    
    [self   requetData];
}

-(void)requetData{
    
    
    [NetWork   searchInventoryLaterCallBack:^(id result, NSError *error) {
       
        
        if (!error) {
        
            NSDictionary  *dicResult=(NSDictionary  *)result;
            arrMainData=dicResult[@"verder"];
            _arrStock=dicResult[@"arrMain"];
            if (arrMainData.count) {
               
                Invertory  *invertory=arrMainData[0];
                for (int i=0; i<_arrStock.count; i++) {
                    Stock  *stock=_arrStock[i];
                    if (stock.StockID==invertory.FRecycleStockID) {
                         currentStock=stock;
                         _lableSelectTitle.text=currentStock.StockName;
                        break;
                    }
                }
                
            }
            else{
                self.ViewBottom.hidden=YES;
                self.btnAdd.hidden=YES;
                [CMCCIOTTipsCenter showErrorWithStatus:@"未生成配货单，请联系航食确认实际配货数量并记录实际回收数量，后续补录"];
                if (_arrStock.count) {
                    Stock  *stock=_arrStock[0];
                    _lableSelectTitle.text=stock.StockName;
                   
                }
            }
        }
        [self  resetFrame:arrMainData.count];
        [_tableView  reloadData];
    }];
    
}

#pragma mark Tableview Deleget

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return arrMainData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    PickingInventory   *cell=[tableView dequeueReusableCellWithIdentifier:@"InventoryListPanDianCell"];
    HangBanInfo  *hangBan=[HangBanInfo currentHangBan];
    if ([hangBan.FIsInventoryHS  isEqualToString:@"1"]) {
        cell.selectionStyle=UITableViewCellSelectionStyleNone ;
    }
    Invertory  *invertory=arrMainData[indexPath.row];
    
    cell.lableShopName.text=invertory.FName;
    cell.PeiSongNum.text=[NSString  stringWithFormat:@"%ld",(long)invertory.FDispatchQty]  ;
    
    cell.lablePanDianNum.text=[NSString  stringWithFormat:@"%ld",(long)invertory.FInventoryQty];
    
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 45;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    HangBanInfo  *hangBan=[HangBanInfo currentHangBan];
    
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.saleType==saleAfter&&[hangBan.FIsInventoryHS  isEqualToString:@"1"]) {
        return;
    }
    
    
    Invertory *invertory=arrMainData[indexPath.row];
    
    [CMCCIOTTipsCenter  showAlertTextFieldTitle:@"修改数量" message:@"" andTFOne:^(UITextField * _Nullable textField) {
        
        UIView  *leftView=[[UIView alloc]  initWithFrame:CGRectMake(0, 0, 10, 10)]          ;
        textField.leftView=leftView;
        textField.leftViewMode=UITextFieldViewModeAlways;
        textField.keyboardType=UIKeyboardTypeNumberPad ;
        [[NSNotificationCenter  defaultCenter]  addObserver:self selector:@selector(textFieldChange:) name:UITextFieldTextDidChangeNotification object:textField];
        textNumBer=textField;
        textField.text=[NSString stringWithFormat:@"%ld",(long)invertory.FInventoryQty] ;
        
        
    } andTFTwo:nil cancelTitle:@"取消" cancelBlock:^(CMCCIOTIGAlertActionCustomer * _Nullable action) {
        
        
        ;
    } quireTitle:@"确定" quireBlock:^(CMCCIOTIGAlertActionCustomer * _Nullable action) {
        
        if (textNumBer.text.length) {
            NSString  *shopNumber= textNumBer.text;
            Invertory *invertory=arrMainData[indexPath.row];
            invertory.FInventoryQty=[shopNumber  integerValue];
            
            [arrMainData  replaceObjectAtIndex:indexPath.row withObject:invertory];
            
            [tableView  reloadData];
            
        }
        ;
    }];
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}


- (IBAction)cancel:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma  mark  点击事件

- (IBAction)popBack:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
    
    
}


-(void)textFieldChange:(NSNotification  *)notification{
    
    UITextField  *textField=[notification   object ];
    if (textField.text.length>6) {
        textField.text=[textField.text substringToIndex:6];
    }
    
}


- (IBAction)subBtn:(id)sender {
    
    if (!arrMainData.count) {
        return;
    }
    
    NSMutableDictionary  *dicParama=[[NSMutableDictionary  alloc]  init];
    
    
    HangBanInfo  *hangBanInfo=[HangBanInfo  currentHangBan];
    NSString  *FFLIGHTNUMBER=hangBanInfo.FFLIGHTNUMBER;
    NSString  *FFLIGHTDATE=hangBanInfo.FFLIGHTDATE;
    
    [dicParama  setObject:FFLIGHTNUMBER forKey:@"FFLIGHTNUMBER"];
    [dicParama  setObject:FFLIGHTDATE forKey:@"FFLIGHTDATE"];
    
    [dicParama setObject:[NSNumber numberWithInteger:hangBanInfo.FID ] forKey:@"FID"];
    
    Invertory  *vertory=arrMainData[0];
    [dicParama  setObject:vertory.InvoiceGoodNo forKey:@"InvoiceGoodNo"];
    [dicParama setObject:@"2" forKey:@"FInventoryType"];
    [dicParama setObject:[NSNumber numberWithInteger:currentStock.StockID] forKey:@"FRecycleStockID"];
    [dicParama setObject:[MemberList currentUsinfo].userAccount forKey:@"userAccount"];
    
    
    NSMutableArray *arrData=[NSMutableArray  new];
    for (int i=0; i<arrMainData.count; i++) {
        
        Invertory  *verTem=arrMainData[i];
        
        NSDictionary  *dicTem=@{@"FDispatchQty":[NSNumber numberWithInteger:verTem.FDispatchQty],@"FInventoryQty":[NSNumber numberWithInteger:verTem.FInventoryQty],@"FName":verTem.FName,@"FNumber":[NSString stringWithFormat:@"%@",verTem.FNumber],@"ID":[NSString stringWithFormat:@"%ld",(long)verTem.ID],@"InvoiceGoodNo":verTem.InvoiceGoodNo,@"FRecycleStockID":[NSNumber numberWithInteger:verTem.FRecycleStockID]};
        
        if (self.saleType==saleAfter&&verTem.FInventoryQty<=0) {
            continue;
            
        }
        [arrData  addObject:dicTem];
    }
    
    [dicParama  setObject:arrData forKey:@"list"];
    NSDictionary  *desStr= [CMCCIOTIGUnity   getRequestJson:dicParama];
    [[NetworkFactory  alloc]  startPostRequestWithURL:GetInventoryHSH andPostValues:desStr andSuccessBlock:^(NSDictionary *responseJson) {
        
        if ([responseJson[@"IsSuccess"]  integerValue]==1) {
            
            if (self.saleType==startSales) {
                
                HangBanInfo  *hangBan= [HangBanInfo  currentHangBan];
                hangBan.FIsInventory=@"1";
                [self performSegueWithIdentifier:@"SellingViewController" sender:@"SellingViewController" ];
            }
            else{
                [CMCCIOTTipsCenter  showSuccessWithStatus:responseJson[@"message"]];
                HangBanInfo  *hangBan=[HangBanInfo currentHangBan];
                hangBan.FIsInventoryHS=@"1";
                
                [self.navigationController  popViewControllerAnimated:YES];
            }
            
        }
        
        
    } andFailBlock:^(NSError *error) {
        
        
    } ];
    
    
    
    
}
- (IBAction)addInvertory:(id)sender {
    
    [self performSegueWithIdentifier:@"addInventory" sender:@"addInventory" ];
    
}

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(nullable id)sender NS_AVAILABLE_IOS(5_0){
    
    
    if([sender  isEqualToString:@"addInventory"]){
        
        AddInventoryViewController  *addInvertory=segue.destinationViewController;
        
        addInvertory.vertoryBlock=^(NSDictionary *dicData){
            
            NSDictionary  *dicParama=dicData;
            
            Invertory  *vertory=[[Invertory  alloc]  init];
            vertory.FDispatchQty=0;
            vertory.FInventoryQty=0;
            vertory.FName=STRING_FORMAT(dicParama[@"FName"]);
            vertory.FNumber=STRING_FORMAT(dicParama[@"FNumber"]);
            vertory.ID=[dicParama[@"FID"]  integerValue];
            vertory.InvoiceGoodNo=@"";
            
            __block  BOOL  isHas=NO;
            
            [arrMainData enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                Invertory  *vertoryTem=(Invertory  *)obj;
                if(vertoryTem.ID== vertory.ID){
                    isHas=YES;
                    *stop=YES;
                    
                }
                ;
                
            }];
            
            isHas?nil:[arrMainData  addObject:vertory];
            [self  resetFrame:arrMainData.count];
            
            [_tableView  reloadData];
            
        };
        
    }
    else{
        
    
        
    }
    
    
}

-(void)resetFrame:(NSInteger )index{
    
    
    HangBanInfo  *hangBan=[HangBanInfo currentHangBan];
    
    float maxHeight=0;
    
    if ([hangBan.FIsInventoryHS  isEqualToString:@"1"]) {
        
        self.viewHeight.constant=index*45+35;
        maxHeight=SCREEN_HEIGHT-164;
    }
    else{
        self.viewHeight.constant=index*45+80;
        maxHeight=SCREEN_HEIGHT-235;
    }
    
    _tableView.scrollEnabled=NO;
    
    
    if (self.viewHeight.constant>maxHeight) {
        
        self.viewHeight.constant=maxHeight;
        _tableView.scrollEnabled=YES;
    }
    
    
}

- (IBAction)btnSelectTitle:(id)sender {
    
    if (_arrStock.count) {
        NSMutableArray  *arrAction=[NSMutableArray new];
        
        for ( NSInteger i =0; i<_arrStock.count; i++) {
            
            Stock  *stock=_arrStock[i];
            
            CMCCIOTIGAlertActionCustomer  *actionCustomer=  [CMCCIOTIGAlertActionCustomer  actionCustomerWithTitle:stock.StockName style:UIAlertActionCustomeStyleDarkGray  handler:^(CMCCIOTIGAlertActionCustomer * _Nullable action) {
                
                currentStock=action.userInfo;
                _lableSelectTitle.text=currentStock.StockName;
                
            }];
            if (currentStock==stock) {
                actionCustomer.isSelect=YES;
            }
            actionCustomer.userInfo=stock;
            [arrAction addObject:actionCustomer];
            
        }
        
        [CMCCIOTTipsCenter   showAlertAddressTitle:@"选择仓库" message:@"" arrAction:arrAction];
    }
    
}


@end
